/*
 * Copyright 2012 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package wbbs.web;

import cn.webwheel.DefaultAction;
import cn.webwheel.LogicException;
import cn.webwheel.results.RedirectResult;
import com.google.inject.Inject;
import wbbs.domain.User;
import wbbs.service.LoginService;
import wbbs.service.UserService;

import java.sql.SQLException;

public class BaseAction extends DefaultAction {

    @Inject
    protected LoginService loginService;

    @Inject
    protected UserService userService;

    protected User loginUser;

    public User getLoginUser() throws SQLException {
        if (loginUser != null) return loginUser;
        String uid = loginService.getLoginUserId();
        if (uid == null) return null;
        return loginUser = userService.findUser(uid);
    }

    protected void ensureLoginAction() throws SQLException {
        notNull(getLoginUser(), "登录超时");
    }

    protected void ensureLoginPage() throws SQLException {
        if (getLoginUser() == null) {
            throw new LogicException(new RedirectResult("/login.html"));
        }
    }

    public String shorten(String s, int len) {
        if (s == null) return null;
        if (s.length() <= len) return s;
        return s.substring(0, len) + "...";
    }
}
